package lew.bing.exp.spr.filters;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Base64.Decoder;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by 刘国兵 on 2018/7/28.
 */
@Component
public class WebBasicAuthFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(WebBasicAuthFilter.class);

    String username;
    String pwd;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        username = filterConfig.getInitParameter("username");
        pwd = filterConfig.getInitParameter("pwd");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if(request instanceof HttpServletRequest) {
            HttpSession session = ((HttpServletRequest) request).getSession();
            if (session.getAttribute("basic") != null) {
                chain.doFilter(request,response);
            } else {
                if (!checkAuth((HttpServletRequest) request,(HttpServletResponse) response)) {
                    HttpServletResponse res= (HttpServletResponse) response;
                    res.setStatus(401);
                    res.setHeader("Cache-Control", "no-store");
                    res.setDateHeader("Expires", 0);
                    res.setHeader("WWW-authenticate", "Basic Realm=\"test\"");
                }else {
                    chain.doFilter(request,response);
                }
            }
        } else {
            chain.doFilter(request,response);
        }
    }

    private boolean checkAuth(HttpServletRequest request, HttpServletResponse response) {
        String auth = request.getHeader("Authorization");
        if ((auth != null) && (auth.length() > 6)) {
            auth = auth.substring(6, auth.length());

            String decodedAuth = getFromBASE64(auth);
            if (decodedAuth != null) {
                String[] split = decodedAuth.split(":");
                if (split.length >= 2) {
                    String username = split[0];
                    String password = split[1];
                    if (StringUtils.pathEquals(username,this.username) && StringUtils.pathEquals(password,this.pwd)) {
                        request.getSession().setAttribute("basic",true);
                        return true;
                    }
                }

            }
        }
        return false;
    }

    private String getFromBASE64(String s) {
        if (s == null)
            return null;
        Decoder decoder = Base64.getDecoder();
        try {
            byte[] b = decoder.decode(s);
            return new String(b);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void destroy() {

    }
}
